package com.bruce.downloader.print;

import java.util.concurrent.atomic.LongAdder;

/**
 * 简易下载过程信息实体
 * <br>CreateDate  2021/09/15 16:55:39
 *
 * @author luotuan
 * @version 1.0.0
 */
public class SimpleDownloadProcessInfo {

    private static final double MB = 1024d * 1024d;
    /**
     * 文件大小
     */
    private long contentLength;

    /**
     * 下载速度
     */
    private int speed;

    /**
     * 已下载大小
     */
    private static volatile LongAdder downSize = new LongAdder();

    /**
     * 剩余时间
     */
    private String remainTime;

    /**
     * 前一次下载大小
     */
    private double preDownSize;

    public void print() {
        String downInfo = String.format(("已下载%smb/%smb,速度%skb/s,剩余时间%ss"),
                String.format("%.2f",downSize.doubleValue() / MB), String.format("%.2f",contentLength / MB), speed, remainTime);
        if(!remainTime.equals("NaN") && !remainTime.equals("Infinitys")){
            System.out.print("\r");
            System.out.print(downInfo);
        }
    }

    public long getContentLength() {
        return contentLength;
    }

    public SimpleDownloadProcessInfo setContentLength(long contentLength) {
        this.contentLength = contentLength;
        return this;
    }

    public int getSpeed() {
        return speed;
    }

    public SimpleDownloadProcessInfo setSpeed(int speed) {
        this.speed = speed;
        return this;
    }

    public static LongAdder getDownSize() {
        return downSize;
    }

    public static void setDownSize(LongAdder downSize) {
        SimpleDownloadProcessInfo.downSize = downSize;
    }

    public String getRemainTime() {
        return remainTime;
    }

    public SimpleDownloadProcessInfo setRemainTime(String remainTime) {
        this.remainTime = remainTime;
        return this;
    }

    public double getPreDownSize() {
        return preDownSize;
    }

    public SimpleDownloadProcessInfo setPreDownSize(double preDownSize) {
        this.preDownSize = preDownSize;
        return this;
    }

    public void calculate(){
        // 速度
        setSpeed((int) ((downSize.doubleValue() - getPreDownSize()) / 1024d));
        preDownSize = downSize.doubleValue();
        // 剩余文件大小
        double remainSize = contentLength - downSize.doubleValue();
        // 计算剩余时间
        setRemainTime(String.format("%.1f", remainSize / 1024d / speed));
    }
}
